package com.stu.service.impl;

import com.stu.service.ServiceInstanceBase;
import com.vmware.vim25.mo.*;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: learn_used_code
 * @packageName: com.stu.service
 * @className: com.stu.service-> HostSystemManager
 * @createDate: 2022-03-22 18:22
 * @author: ZhangSheng
 * @version: 1.0
 * @description:
 */
@Service
public class HostSystemManager implements ServiceInstanceBase{


    @Override
    public ServiceInstance connection(String ipAddress, int port, String username, String password) throws MalformedURLException, RemoteException {
        URL url = new URL("https",ipAddress, port, "/sdk");
        return new ServiceInstance(url,username,password,true,30 * 1000, 60 * 1000);
    }


    @Override
    public List<HostSystem> getHostSystemList(ServiceInstance serviceInstance) throws RemoteException {
        ManagedEntity[] entities = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("HostSystem");
        List<HostSystem> hostSystems = new ArrayList<>();
        if (entities == null || entities.length <= 0){
            return new ArrayList<>();
        }
        for (int i = 0; i < entities.length; i++) {
            HostSystem entity = (HostSystem)entities[i];
            hostSystems.add(entity);
        }
        return hostSystems;
    }


    @Override
    public List<VirtualMachine> getVirtualMachineList(ServiceInstance serviceInstance) throws RemoteException {
        List<VirtualMachine> virtualMachineList = new ArrayList<>();
        ManagedEntity[] entities = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("VirtualMachine");
        if (entities == null || entities.length <=0){
            return new ArrayList<>();
        }
        for (int i = 0; i < entities.length; i++) {
            VirtualMachine virtualMachine = (VirtualMachine)entities[i];
            virtualMachineList.add(virtualMachine);
        }
        return virtualMachineList;
    }


    @Override
    public VirtualMachine getSingleVm(ServiceInstance serviceInstance,String morId) throws RemoteException {
        InventoryNavigator inventoryNavigator = new InventoryNavigator(serviceInstance.getRootFolder());
        ManagedEntity[] managedEntities = inventoryNavigator.searchManagedEntities("VirtualMachine");
        if (managedEntities == null || managedEntities.length <=0){
            return null;
        }
        for (int i = 0; i < managedEntities.length; i++) {
            VirtualMachine virtualMachine = (VirtualMachine)managedEntities[i];
            if (virtualMachine.getMOR().getVal().equals(morId)){
                return virtualMachine;
            }
        }
        return  null;
    }




}